package cn.com.gzheroli.core.manager;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import cn.com.gzheroli.cache.ProtoStuffSerializerUtil;
import cn.com.gzheroli.cache.SpringRedisCache;
import cn.com.gzheroli.core.util.ApplicationContextUtil;


/**
 * 对在线用户的管理
 * @version 1.0
 */
@Service
public class ClientManager {
	
	private static ClientManager instance = new ClientManager();
	private static int  exp=10;
	private static String  allUser="allUser";
	
	@Autowired
    private SpringRedisCache springRedisCache;
	
	private ClientManager(){
		if(springRedisCache==null){
			springRedisCache=ApplicationContextUtil.getBean("springRedisCache");
		}
	}
	@PostConstruct 
	public void initCache(){
		
	}
	public static ClientManager getInstance(){
		return instance;
	}
	
	private Map<String,Client> map = new HashMap<String, Client>();
	
	/**
	 * 
	 * @param sessionId
	 * @param client
	 */
	public void addClinet(String sessionId,Client client){
		//map.put(sessionId, client);
		springRedisCache.putCacheWithExpireTime(sessionId, ProtoStuffSerializerUtil.serialize(client), exp);
		//Map allUserMap=JedisUtil.hgetAll(allUser);
		/*List userList=JedisUtil.lrange(allUser, 0, -1);  
		if(userList==null||userList.isEmpty())
			userList=new ArrayList();
		if(!userList.contains(client.getUser().getUserName()))
			JedisUtil.lpush("allUser",client.getUser().getUserName());*/
		//JedisUtil.setnx(client.getUser().getUserName(), sessionId);
	}
	/**
	 * sessionId
	 */
	public void removeClinet(String sessionId){
		//map.remove(sessionId);
		Client client=getClient(sessionId);
		springRedisCache.deleteCache(sessionId);
		/*JedisUtil.del(sessionId.getBytes());
		
		JedisUtil.del(client.getUser().getUserName());*/
	}
	/**
	 * 
	 * @param sessionId
	 * @return
	 */
	public Client getClient(String sessionId){
		//return map.get(sessionId);
		return springRedisCache.getCache(sessionId, Client.class);
		//return ProtoStuffSerializerUtil.deserialize(JedisUtil.get(sessionId.getBytes()), Client.class);
	}
	/**
	 * 
	 * @return
	 */
	public Collection<String> getAllClient(){
		/*List allUserList=JedisUtil.lrange(allUser, 0, -1); 
		//return map.values();
		return allUserList;*/
		return null;
	}

}
